const pool = require('../tools/getPool');
const sendResponse = require('../tools/sendResponse');

module.exports = function(req, res){

	let id = req.body.id;
	let oldpassword = req.body.oldpassword;
	let newpassword = req.body.newpassword;

	let sql = '';
	let params = [];

	if (oldpassword == undefined || oldpassword == "" || newpassword == undefined || newpassword == ""){
		sendResponse('error','缺少参数，请检查', null, res);
		return; 
	}


	// 获取数据库连接
	pool.getConnection(function(err, connection) {
		if (err) {
			console.log(err);
			sendResponse('error','数据库内部错误', null, res);
			return;
		}

		connection.query('SELECT account FROM admin WHERE id = ? and password = ?', [id,oldpassword], function (error, rows, fields) {

			if (error) { 
				sendResponse('error','database error', null, res);
				return;
			} else {
				// 匹配成功，旧密码是对的
				if (rows.length == 1) {
					connection.query('UPDATE admin SET password = ? WHERE id = ?', [newpassword, id], function (error, rows, fields) {
						connection.release();
						if (error) { 
							sendResponse('error','数据库内部错误', null, res);
						} else {
							sendResponse('ok','修改成功', null, res);
							return;
						}

					})

				} else {
					sendResponse('error','密码错误', null, res);
					return;
				}

			}

		})

	});

}